/**
 * 费用申请模块业务入口
 */
import presetVar from './presetVar';
import React, { Component } from 'react';
import { createPage, base, high, getMultiLang ,pageTo,promptBox} from 'nc-lightapp-front';
import { tableButtonClick, pageButtonClick, afterEvent, beforeEvent, refreshButtonClick } from './events';
import initTemplate, {routeChange} from './initTemplate';
import { getAfterEventParams } from 'src/erm/sscrppublic/common/utils/formulaUtils';
import pubMessage from 'src/erm/sscrppublic/common/utils/pubMessage';
import AdjustRelationSearch from '../../adjustRelation/list/adjustRelationSearch';
import Inspection from 'epmp/exports/components/Inspection';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import attachments from 'uap/common/components/getAttachmentInfo';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import { setTable } from 'src/erm/sscrppublic/common/utils/setComponentUsed'
import BillApprove from 'uap/common/components/BillApprove';
//引入侧边栏
import AuditSidebar from 'sscia/auditSidebar/components/auditSidebar'
const { getAttachments, getAttachmentsInfo } = attachments;
let { NCModal } = base;
import {
    BillStyle,
    BillHead,
    BillBody,
    Form,
    CardTable,
    ButtonGroup
} from 'src/erm/sscrppublic/common/components/bill';

import { EditTable } from 'src/erm/sscrppublic/common/components/table';
import './index.less';

const pageButton = presetVar.pageButton;
const body1 = presetVar.body.body1;
const head1 = presetVar.head.head1;

window.assingUsers = [];
window.sureAssign = false;//确定指派
window.assignBillId = '';//有指派的情况下，第一次点保存提交实际保存成功的单据pk

// window.billinfo = {
//     tzd_billid: '',
//     tzd_billno: '',
//     tzd_tradetype: ''
// };

class Adjustment extends Component {

    constructor(props) {
        super(props);
        //初始化侧边栏
        this.auditSidebar = new AuditSidebar();
        props.use.form('head');
        setTable(props, 'linkrelationbill');
        /* if (NODE_ENV == 'development') {
            window.NODE_ENV = 'development';
        } */
        this.state = {
            showApprovePanel: false,
            showUploader: false,
            ShowApproveDetail: false,
            billtype: '',
            billId: '',
            compositedata: '',
            compositedisplay: '',
            sourceData: null,
            showLinkBudget: false,
            title: '',
            showRelationModal: false,
            linkRelationBillModal: false,
            uploaderBtnDisable: false,
            djzt:'0',
            showAuditSidebar:false,
        }
        this.billId = props.getUrlParam('billid');
        this.pubMessage = new pubMessage(props);

        initTemplate.call(this, props);
        this.haedLayout = function (multiLang, btnModalConfig, head1) {
            return (

                <BillHead
                    // "201102TZFY-0001": "费用调整单"
                    title={this.state.title}
                    refreshButtonEvent={refreshButtonClick.bind(this)}
                >
                    <ButtonGroup
                        areaId={presetVar.head.head2}
                        buttonEvent={pageButtonClick.bind(this)}
                        modalConfig={btnModalConfig}
                        sagasButtonVisible={true}
                    />

                    <Form
                        areaId={head1}
                        onAfterEvent={afterEvent.bind(this)} //表体编辑后事件
                    />
                </BillHead>
            )
        }

        // TOP NCCLOUD-61317 增加公式编辑后联动 chengwebc ADD
        props.setRelationAfterEventCallBack && props.setRelationAfterEventCallBack((props, changedField, changedArea, oldCard, newCard, index, rowId) => {
            let params = getAfterEventParams(props, changedField, changedArea, oldCard, newCard, index, rowId);
            params.map((one) => {
                afterEvent.call(this, props, one.moduleId, one.key, one.value, one.changedrows, one.index)
            })
        });
        // BTM NCCLOUD-61317 增加公式编辑后联动 chengwebc

        //关联成功后需要关闭modal
        window.closeRelation = () => {
            this.setState({
                showRelationModal: false
            })
        }
    }

    componentDidMount() {
        this.props.setHashChangeCallback(() => {
            routeChange.call(this, this.props);
      })
    }
    componentWillMount() {
        window.onbeforeunload = () => {
            let status = this.props.getUrlParam("status");
            if (status == 'edit' || status == 'add') {
                return ''/* 国际化处理： 确定要离开吗？*/
            }
        }
    }
    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    closeApprove = () => {
        this.setState({
            ShowApproveDetail: false
        })
    }
    getAssginUser = (value) => {
        window.assingUsers = value;
        window.sureAssign = true;
        pageButtonClick.call(this)[pageButton.Submit]();
        window.assignBillId = '';
    }

    turnOff() {
        window.presetVar.fromBtn = 'turnOff'
        this.setState({
            compositedisplay: false
        });
        window.sureAssign = false;
        window.assingUsers = [];
        let props = this.props;
        let billid = window.assignBillId;
        if (!billid) {
            let billdata = props.createExtCardData(presetVar.nccPageCode, head1, [body1]);
            let headValues = billdata.head[head1].rows[0].values;
            billid = headValues.pk_jkbx.value;
        }
        pageTo.specialLinkTo(location.pathname, {
            status: presetVar.status.browse,
            id: billid,
            scene: presetVar.scene
        })
        routeChange.call(this, this.props)

    }
    cancel() {
        this.setState({
            showLinkBudget: false
        })
    }
    affirm(info) {
        this.setState({
            showLinkBudget: false
        })
    }
    closeRelation() {
        this.setState({
            showRelationModal: false
        })
    }
    uploaderOnHide() {
        this.setState({ showUploader: false });
        let multiLang = this.props.MutiInit.getIntl(2011);
        getAttachments(presetVar.openBillId).then((count) => {
            this.props.button.setButtonTitle('File', multiLang&&multiLang.get('201102TZFY-0003')/**'附件'**/ + ' ' + String(count) + ' ');
        })
    }

    setRelationChecked = (data, relationProps) => {
        let relatedPks = [];
        data.grid && data.grid.rplist && data.grid.rplist.rows && data.grid.rplist.rows.forEach((row) => {
            let relatePk = row.rowId ? row.rowId : row.values.pk_bill && row.values.pk_bill.value;
            relatedPks.push(relatePk);
        })
        relationProps.transferTable.setTheCheckRows(window.presetVar.list, relatedPks);
    }
    // 云原生环境
    renderErrorCenterState () {
        const { props } = this
        const status = props.form.getFormItemsValue(head1, 'saga_status')
        if (!status || status.value !== '1') return null;

        this.props.button.toggleErrorStatus('head',{
            isError: true
        })
        window.___props = props
        const param = {
            headBtnAreaCode: 'head',
            formAreaCode: head1,
            billtype: status.value,
            billpkname: 'pk_jkbx',
            dataSource: 'erm.expenseaccount.adjustment.card'
        }
        return props.socket.connectMesg(param)
    }
    toggleAuditSideBar(fromBtn) {
        //判断是否是提交 按钮或者保存提交按钮
        fromBtn = fromBtn||window.presetVar.fromBtn
       
        const pageId = window.presetVar.pageId;
        let billdata = this.props.createMasterChildData(pageId, head1, body1);
        let headValues = billdata.head[head1].rows[0].values;
       
        let param = {};
        param.pk_group = headValues.pk_group.value; // "集团pk"
        param.billtypecode = headValues.djlxbm.value; // "单据类型code" 
        param.tradetypecode = presetVar.tradeType; // " 交易类型code"
        param.billid = this.props.getUrlParam('billid') ||  this.props.getUrlParam('id') || this.state.billId || presetVar.openBillId;; // "单据主键pk"
        param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        param.iscreate = "Y"   // 注意应该是制单首次保存传Y,浏览态去掉这个参数！！！是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入 做初始化 智能审批
        param.isEdit = true;

        // param.pk_group = "0001A510000000000NKA"; // "集团pk"
        // param.billtypecode = "267X"; // "单据类型code" 
        // param.tradetypecode = "267X"; // " 交易类型code"
        // param.billid = "1001A510000000003V27"; // "单据主键pk"
        // param.src_type = "billmaker"; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        // param.iscreate =  "Y"  // 是否初始化单据信息，编辑状态传入 "Y"，浏览态不传  所有环节都传入
        // param.isEdit = true; // billmaker:制单、 approve: 审批中心、 ssc: 共享
        console.log('param111111111111111111111',param,this.props.getUrlParam("status"),this.props.getUrlParam("scene"))
        if(!param.billid){
            return
        }
        //展示后的回调
        this.auditSidebar.showSidebar(param,null,()=>{
            // this.auditSidebar.refreshSidebar()
            setTimeout(()=>{
                const auditSidebarObj = this.auditSidebar.getSidebarStatistical()
                console.log('1111111',auditSidebarObj)
                const {pointTree} = auditSidebarObj
                if(!pointTree.length){
                    this.setState({
                        showAuditSidebar:false
                    })
                    window.presetVar.auditCanSave = 0
                    return
                }
                this.setState({
                    showAuditSidebar:true
                })

                for(let i=0;i<pointTree.length;i++){
                    const leaf = pointTree[i]
                    if(leaf.children&&leaf.children.length){
                        if(leaf.children.some(item=>item.ispass==='N')){
                            window.presetVar.auditCanSave = 3 //目前需求只要有不通过的就提示风险
                            //1 严格控制 2风险提示
                            // if(leaf.children.some(item=>item.values.controltype=='1')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 1
                            //     break
                            // }else if(leaf.children.some(item=>item.values.controltype=='2')){
                            //     //1 严格控制 2风险提示
                            //     window.presetVar.auditCanSave = 2
                            //     break
                            // }
                        }else{
                            window.presetVar.auditCanSave = 0
                        }
                    }
                }
                
                //展示风险弹窗
                if(fromBtn==='saveSubmit'&&this.props.getUrlParam("status")==='browse'&&window.presetVar.auditCanSave>0){
                    let multiLang = this.props.MutiInit.getIntl(2011);
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0016'),
                        content: multiLang && multiLang.get('201102BCLF-0062'),
                        cancelBtnName:'收回',
                        beSureBtnClick: ()=>{
                            window.presetVar.auditCanSave = 0
                            
                        },
                        cancelBtnClick: () => {
                            pageButtonClick.call(this)[pageButton.Recall]();
                            
                        }
                    })   
                }
            })
            
        })
        
    }
    getFormHeadValueByKey(key) { // 根据 form 获取 head 中的值
        return this.props.form.getFormItemsValue("head", key).value || '';
    }
    render() {
        const { table,DragWidthCom } = this.props;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createSimpleTable } = table;
        let { djzt,showAuditSidebar } = this.state;
        let status = this.props.getUrlParam("status");
        let scene = this.props.getUrlParam("scene");
        let btnModalConfig = {
            [pageButton.Delete]: {
                // "2011-0004": "删除",
                // "2011-0005": "确认删除该单据吗？"
                title: multiLang && multiLang.get('2011-0004'),
                content: multiLang && multiLang.get('2011-0005')
            },
            [pageButton.Invalid]: {
                // "2011-0009": "作废",
                // "2011-0010": "确认作废该单据吗？"
                title: multiLang && multiLang.get('2011-0009'),
                content: multiLang && multiLang.get('2011-0010')
            },
            [pageButton.billEnable]: {
                // "2011-0011": "重启",
                // "2011-0012": "确认重启该单据吗？"
                title: multiLang && multiLang.get('2011-0011'),
                content: multiLang && multiLang.get('2011-0012')
            },
            [pageButton.billClose]: {
                // "2011-0007": "关闭",
                // "2011-0013": "确认关闭该单据吗？",
                title: multiLang && multiLang.get('2011-0007'),
                content: multiLang && multiLang.get('2011-0013')
            }
            
        }
        return (

            <div className='billWrapper' style={{overflow: 'scroll'}}>
                {this.renderErrorCenterState()}
                <DragWidthCom
                    leftDom={
                        <BillStyle
                            {...this.props}
                        >
                            {this.haedLayout(multiLang, btnModalConfig, head1)}

                            <BillBody>

                                <CardTable
                                    // "201102TZFY-0002": "费用申请单明细",
                                    title={multiLang && multiLang.get('201102TZFY-0002')} //表体表体
                                    areaId={body1}       //表体区域id
                                    totalItemCode="assume_amount"   //表体的统计字段
                                    modelSave={pageButtonClick.call(this)[pageButton.Save]} //卡片上的整单保存按钮
                                    onAfterEvent={afterEvent.bind(this)} //表体编辑后事件
                                    onBeforeEvent={beforeEvent.bind(this)}
                                    modelDelRow={() => {
                                        console.log(888);
                                    }}
                                >
                                    <ButtonGroup
                                        // areaId={body1 + "_card_body"}  //按照默认区域规则配置，这里可以不配置
                                        buttonEvent={tableButtonClick.bind(this)} //仅使用默认按钮，这里也可以不配置
                                    />
                                </CardTable>

                                <div>
                                    {this.state.showUploader && < NCUploader
                                        disableButton={this.state.uploaderBtnDisable}
                                        billId={presetVar.openBillId}
                                        targrt={null}
                                        placement={'bottom'}
                                        onHide={this.uploaderOnHide.bind(this)}
                                    />
                                    }
                                </div>
                                <div>
                                    <ApproveDetail
                                        show={this.state.ShowApproveDetail}
                                        close={this.closeApprove}
                                        billtype={this.state.billtype}
                                        billid={this.state.billId}
                                    />
                                </div>

                                <BillApprove
                                    show={this.state.showApprovePanel}
                                    close={() => this.setState({ showApprovePanel: false })}
                                    billtype={presetVar.tradeType}
                                    billid={this.billId}
                                />
                                <div>
                                    {/*"201102FYYT-0003": "指派",*/}
                                    {this.state.compositedisplay ? <ApprovalTrans
                                        title={multiLang && multiLang.get('201102FYYT-0003')}
                                        data={this.state.compositedata}
                                        display={this.state.compositedisplay}
                                        getResult={this.getAssginUser}
                                        cancel={this.turnOff.bind(this)}
                                    /> : ""}

                                </div>
                                <div>
                                    <Inspection
                                        show={this.state.showLinkBudget}
                                        sourceData={this.state.sourceData}
                                        cancel={this.cancel.bind(this)}
                                        affirm={this.affirm.bind(this)}
                                    />
                                </div>
                            </BillBody>
                        </BillStyle>
                    }
                    rightDom={
                        this.auditSidebar.createComponent()
                    }
                    aside="right"
                    defLeftWid={showAuditSidebar && djzt !== '0' && status === 'browse' && (scene !== 'sscermlink' && scene !== "linksce" && scene !== "lc" && scene !== "approve" && scene !== "approvesce" && scene !== 'zycl')
                        ? "20%" : '0%'}
                >

                </DragWidthCom>
                

                <NCModal size="xlg"
                    show={
                        this.state.showRelationModal
                    }
                    onHide={
                        this.closeRelation.bind(this)
                    }
                >

                    <NCModal.Header closeButton="true">
                        {/*"201102BCLF-0002": "冲借款",*/}
                        <NCModal.Title >{multiLang && multiLang.get('201102BCLF-0057')}</NCModal.Title>
                    </NCModal.Header>

                    <NCModal.Body >
                        <div className="area-content" >
                            {/*<iframe src={window.location.protocol+"//"+window.location.host+"/erm/expenseaccount/adjustRelation/list/index.html"}*/}
                            {/*width="100%" className="relationmodel"></iframe>*/}
                            <AdjustRelationSearch showRelationModal={this.state.showRelationModal} setRelationChecked={this.setRelationChecked} />
                        </div>

                        <div>
                        </div>
                    </NCModal.Body>

                </NCModal>
                {/*联查单据*/}
                <NCModal
                    backdrop='static'
                    size="xlg"
                    show={
                        this.state.linkRelationBillModal
                    }
                    onHide={
                        () => {
                            this.setState({ linkRelationBillModal: false });
                        }
                    }
                >
                    {/*联查单据*/}
                    <NCModal.Header closeButton="true">
                        {/* 联查单据 */}
                        <NCModal.Title>{multiLang && multiLang.get('201102HKD-0003')}</NCModal.Title>
                    </NCModal.Header>
                    <NCModal.Body>
                        <div className='nc-single-table'>
                        {createSimpleTable('linkrelationbill', {
                            onAfterEvent: afterEvent.bind(this),
                            showCheck: false,
                            showIndex: true,
                        })}
                        </div>
                    </NCModal.Body>
                    <NCModal.Footer></NCModal.Footer>
                </NCModal>
            </div>
        );

    }
}

Adjustment = createPage({
    mutiLangCode: '2011',
    billinfo: {
        billtype: 'card',  //虽然后台是一主多子数据结构，但是配置成extCard，编辑后请求公式验证会报错。因为会根据实际展现的表体数量来判断是一主多子还是一主一子。
        pagecode: presetVar.nccPageCode,
        headcode: head1,
        bodycode: body1
    },
    orderOfHotKey: [body1]
})(Adjustment);

export default Adjustment;
